<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\tiles;


class UserTilesBalance extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_tiles';

    const _CONFIG_SELECT_ = 'db_tiles';

    const _DATABASE_ = 'tiles';

    const _TABLE_NAME = 'user_tiles_balance';

    const STATUS_NORMAL = 1;


    public static function addUserBalance($uid, $tilesNum)
    {
        $userTilesBalance = self::get("*", [
            'uid' => $uid
        ]);
        if ($userTilesBalance) {
            self::update([
                'balance[+]' => $tilesNum,
                'edittime'   => date('Y-m-d H:i:s')
            ], [
                'uid' => $uid,
            ]);
        } else {
            self::insert([
                'uid'      => $uid,
                'balance'  => $tilesNum,
                'addtime'  => date('Y-m-d H:i:s'),
                'edittime' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public static function getUserBalance($uid)
    {
        $userBalance = self::get('*', ['uid' => $uid]);
        return $userBalance ? $userBalance['balance'] : 0;
    }

    public static function consumeUserBalance($uid, $amount)
    {
        $result = self::update([
            'balance[-]' => $amount,
            'edittime'   => date('Y-m-d H:i:s')
        ], [
            'uid'        => $uid,
            'balance[>=]' => $amount
        ]);
        return $result->rowCount();
    }

}